package com.sdd.rpi_mobile.eventRss;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.sdd.rpi_mobile.R;
import com.sdd.rpi_mobile.homeScreen.GridChooser;

/**
 * Shows an item retrieved from an RSS feed and packed into a RssItem
 * If an RssItem is not sent this will fail
 */
public class RSSItemActivity extends Activity {	
	private TextView mTitle, mDesc, mLink, mCateg;

	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rssitem);
		// Enable the Home button in the action bar.
		if (Build.VERSION.SDK_INT >= 14){
			getActionBar().setHomeButtonEnabled(true);
		}
		
		Bundle bundle = this.getIntent().getBundleExtra("rss_bundle");
		RssItem item = null;
		try{
			item = (RssItem) bundle.getSerializable("rss_item");
			if(item == null)
				throw new NullPointerException("No item found");
		}
		catch(NullPointerException e)
		{
			// Setup Title.
			mTitle = (TextView) findViewById(R.id.header);
			mTitle.setText("Unable to load RSS");
		}
		
		// Setup Title.
		mTitle = (TextView) findViewById(R.id.header);
		if(mTitle != null) mTitle.setText(item.getTitle());
		
		// Setup description.
		mDesc = (TextView) findViewById(R.id.item_description);
		if(mDesc != null) mDesc.setText(item.getDescription());
		
		// Setup link.
		mLink = (TextView) findViewById(R.id.item_link);
		if(mLink != null) {
			mLink.setText(item.getLink());
			Linkify.addLinks(mLink, Linkify.ALL);
			Linkify.addLinks(mDesc, Linkify.ALL);
		}
		
		// Setup categories.
		mCateg = (TextView) findViewById(R.id.item_categories);
		if(mCateg != null){
			ArrayList<String> cats = item.getCategories();
			String catText = "";
			for (String cat: cats) catText += cat + ", ";
			mCateg.setText(catText);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.rssitem, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case android.R.id.home:
	            // app icon in action bar clicked; go home
	            Intent intent = new Intent(this, GridChooser.class);
	            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	            startActivity(intent);
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
}
